package com.shao.im.controller;

import com.shao.commons.domain.Codes;
import com.shao.commons.domain.R;
import com.shao.commons.exception.ServiceException;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * 文件上传下载
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    private static final Log LOG = LogFactory.getLog(FileController.class);

    @Value("${file.uploader}")
    private String uploadPath;

    /**
     * 文件上传
     * @return 返回上传成功的文件名
     */
    @RequestMapping("/uploader")
    public R<String> upload(MultipartFile file){

        File filePath = new File(uploadPath);
        if (!filePath.exists()) {
            boolean flag = filePath.mkdirs();
            if (!flag) {
                LOG.error("文件 " + uploadPath + " --> 上传失败！");
            }
        }

        //准备文件名称
        String fileName = UUID.randomUUID().toString();

        //
        try (
                InputStream in = file.getInputStream();
                OutputStream out = new FileOutputStream(new File(filePath, fileName))
        ){
            IOUtils.copy(in, out);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return R.success(fileName);
    }

    /**
     * 文件的下载
     * @param fileName 文件名
     * @param response response
     */
    @RequestMapping("/download")
    public void download(String fileName, HttpServletResponse response){
        File file = new File(uploadPath, fileName);
        if (!file.exists())
            throw new ServiceException(Codes.FILE_NOT_FOUND);

        try(
                InputStream in = new FileInputStream(file);
                OutputStream out = response.getOutputStream()
        ) {
            IOUtils.copy(in, out);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 文件重命名的功能
     */
    @SuppressWarnings("unused")
    public void fileRename(){

    }

    /**
     * 文件过滤
     */
    @SuppressWarnings("unused")
    public void fileFilter(){

    }
}
